<template>
  <ContentWrap class="content-wrapper-1">
    <loginOut :pageName="pageName" />
    <!-- <div class="serial-number"> 开/报工 </div> -->
    <div class="serial-number">
      <el-form
        style="margin-top: 70px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="168px"
      >
        <el-form-item :label="t('opticore.workReport.searchForm.lineId')" prop="lineId">
          <el-select
            v-model="queryParams.lineId"
            class="!w-280px"
            clearable
            :placeholder="t('opticore.workReport.placeholder.line')"
          >
            <el-option
              v-for="item in productLineList"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item :label="t('opticore.workReport.searchForm.equipment')" prop="equipment">
          <el-select
            v-model="queryParams.equipment"
            class="!w-280px"
            clearable
            :placeholder="t('opticore.workReport.placeholder.equipment')"
          >
            <el-option
              v-for="item in deviceList"
              :key="item.equipment"
              :label="item.equipmentName"
              :value="item.equipment"
            />
          </el-select>
        </el-form-item>

        <el-form-item :label="t('opticore.workReport.searchForm.process')" prop="process">
          <el-select v-model="queryParams.process" class="!w-280px" clearable>
            <el-option v-for="item in processList" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div class="report-btn-container">
      <el-radio-group v-model="mode" style="margin-bottom: 20px">
        <el-radio-button label="start">{{ t('opticore.workReport.title.start') }}</el-radio-button>
        <el-radio-button label="report">{{
          t('opticore.workReport.title.report')
        }}</el-radio-button>
        <el-radio-button label="finish">{{
          t('opticore.workReport.title.finish')
        }}</el-radio-button>
      </el-radio-group>
    </div>

    <div class="serial-number">
      <!-- <el-input
        v-model="serial"
        class="serial-input"
        :placeholder="t('opticore.workReport.placeholder.scanWorkOrder')"
        clearable
      >
        <template #prefix>
          <el-icon>
            <Search />
          </el-icon>
        </template>
      </el-input> -->
      <el-autocomplete
        v-model="serial"
        class="serial-input"
        :placeholder="t('opticore.workReport.placeholder.scanWorkOrder')"
        :fetch-suggestions="querySearch"
        @select="handleSelect"
        style="width: 500px"
        clearable
      >
        <template #prefix>
          <el-icon>
            <Search />
          </el-icon>
        </template>
      </el-autocomplete>
    </div>

    <div class="report-btn-container">
      <div v-if="mode == 'report'">
        <el-button type="primary" class="report-btn" @click="handleReport">{{
          t('opticore.workReport.button.report')
        }}</el-button>
      </div>
      <div v-else-if="mode == 'start'">
        <el-button type="primary" class="report-btn" @click="handleStart">{{
          t('opticore.workReport.button.start')
        }}</el-button>
      </div>
      <div v-else>
        <el-button type="primary" class="report-btn" @click="handleFinish">{{
          t('opticore.workReport.button.finish')
        }}</el-button>
      </div>
    </div>
  </ContentWrap>

  <el-dialog
    v-model="showReportDialog"
    :title="t('opticore.workReport.dialog.reportEntry')"
    width="40%"
    :before-close="handleClose"
  >
    <div class="form-container">
      <div class="form-row">
        <span class="form-label">{{ t('opticore.workReport.form.serialNumber') }}：</span>
        <el-input v-model="form.serialId" disabled class="form-value" />
      </div>

      <div class="form-row">
        <span class="form-label">{{ t('opticore.workReport.form.workOrder') }}：</span>
        <el-input v-model="form.workOrder" disabled class="form-value" />
      </div>

      <div class="form-row">
        <span class="form-label required">{{ t('opticore.workReport.form.cableLength') }}：</span>
        <el-input
          v-model="form.quantity"
          :placeholder="t('opticore.workReport.placeholder.enterLength')"
          class="form-input"
        >
          <template #append>M</template>
        </el-input>
      </div>

      <div class="form-row">
        <span class="form-label">{{ t('opticore.workReport.form.reporter') }}：</span>
        <el-input v-model="form.operator" disabled class="form-value" />
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">{{
          t('opticore.workReport.button.printQrCode')
        }}</el-button>
      </div>
    </template>
  </el-dialog>
  <WorkStartForm ref="workStartFormRef" :query-params="queryParams" @success="getList" />

  <!-- 完工 -->
  <el-dialog v-model="showFinishDialog" :title="t('opticore.workReport.table.title')" width="80%">
    <el-table :data="finishList" style="width: 100%">
      <el-table-column prop="serialNo" width="200" :label="t('opticore.workReport.table.index')" />
      <el-table-column
        prop="itemCode"
        :label="t('opticore.workReport.table.serialNumber')"
        width="280"
      />
      <el-table-column prop="itemName" :label="t('opticore.workReport.table.workOrder')" />
      <el-table-column prop="qph" :label="t('opticore.workReport.table.cableLength')" width="180" />
      <el-table-column prop="number" :label="t('opticore.workReport.table.reporter')">
        <template #default="scope">
          <el-input v-model="scope.row.number" type="number" :placeholder="t('common.inputText')" />
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleFinishSubmit"> {{ t('common.ok') }} </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 列表 -->
  <!--  <ContentWrap>
      <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
        <el-table-column label="编号" align="center" prop="id" />
        <el-table-column label="序列号" align="center" prop="serialNo" />
        <el-table-column label="工单号" align="center" prop="docNo" />
        <el-table-column label="产线" align="center" prop="line" />
        <el-table-column label="设备" align="center" prop="equipment" />
        <el-table-column label="工序" align="center" prop="process" />
        <el-table-column label="数量" align="center" prop="qty" />
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          width="180px"
        />
        <el-table-column label="操作" align="center" min-width="120px">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="openForm('update', scope.row.id)"
              v-hasPermi="['opticore:work-report:update']"
            >
              编辑
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleDelete(scope.row.id)"
              v-hasPermi="['opticore:work-report:delete']"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      &lt;!&ndash; 分页 &ndash;&gt;
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>-->
  <!-- 表单弹窗：添加/修改 -->
  <!--  <WorkReportForm ref="formRef" @success="getList" />-->
  <!-- 调用打印组件 -->
  <PrintQrCode
    :visible="printDialogVisible"
    :currentMaterialsItem="selectedMaterialsItem"
    @reset="resetState"
  />
</template>

<script setup lang="ts">
import { WorkReportApi, WorkReportVO } from '@/api/opticore/workreport'
import { ProcessInfoApi } from '@/api/opticore/processinfo'
import { Search } from '@element-plus/icons-vue' // 导入图标，这里用Search代替二维码图标
import { getLineDictDataList } from '@/api/system/dict/dict.data'
import { MaterialUsageApi } from '@/api/opticore/materialusage'
import WorkStartForm from './WorkStartForm.vue'
import { ref, watch } from 'vue'
import { DeviceApi } from '@/api/opticore/device'
import loginOut from '@/components/loginOut/index.vue'
import PrintQrCode from '@/views/customer/material/components/PrintQrCode.vue'
import { computed } from 'vue'
import { MaterialInventorApi } from '@/api/opticore/materialinventor'

/** 报工记录 列表 */
defineOptions({ name: 'WorkReport' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const pageName = computed(() => t('opticore.workReport.title.report'))

const mode = ref('start') // 'report' 或 'start'

watch(mode, () => {
  serial.value = ''

  if (mode.value == 'report') {
    pageName.value = t('opticore.workReport.title.report')

    fetchReportList()
  } else if (mode.value == 'start') {
    pageName.value = t('opticore.workReport.title.start')
    fetchKgList()
  } else if (mode.value == 'finish') {
    pageName.value = t('opticore.workReport.title.finish')
    fetchReportList()
  }
})

const loading = ref(true) // 列表的加载中
const list = ref<WorkReportVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const serial = ref('') //物料序列号
const productLineList = ref([])
const deviceList = ref([])
const processList = ref([])
const showReportDialog = ref(false)
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  serialNo: '',
  docNo: undefined,
  lineId: undefined,
  equipment: undefined,
  process: undefined,
  processCode: undefined,
  qty: undefined,
  createTime: [],
  productId: undefined
})
const queryFormRef = ref() // 搜索的表单

watch(
  () => queryParams.lineId,
  () => {
    console.log(queryParams.lineId)

    serial.value = ''
    // if (mode.value == 'report') {
    //   fetchReportList()
    // } else  {
    //   fetchKgList()
    // }

    if (mode.value == 'report') {
      fetchReportList()
    } else if (mode.value == 'start') {
      fetchKgList()
    } else if (mode.value == 'finish') {
      fetchReportList()
    }
  }
)

const kgList = ref([])

const fetchKgList = () => {
  if (!queryParams.lineId) {
    return
  }
  kgList.value = []

  DeviceApi.getDocNoList({
    lineId: queryParams.lineId
  }).then((res) => {
    kgList.value = res.map((item) => {
      return {
        value: item
      }
    })
  })
}

const reportList = ref([])

const fetchReportList = () => {
  if (!queryParams.lineId) {
    return
  }

  reportList.value = []

  DeviceApi.getReportDocNoList({
    lineId: queryParams.lineId
  }).then((res) => {
    reportList.value = res.map((item) => {
      return {
        value: item
      }
    })
  })
}

const showFinishDialog = ref(false)

const finishList = ref([])

const handleFinish = () => {
  if (!serial.value) {
    message.warning(t('opticore.workReport.message.scanSerial'))

    return
  }
  finishList.value = []

  MaterialInventorApi.getByWorkStartByDocNo(serial.value).then((res) => {
    finishList.value = res
    console.log('finishList', finishList.value)
    showFinishDialog.value = true
  })
}

const handleFinishSubmit = () => {
  const hasEmptyNumber = finishList.value.some((item) => {
    const num = Number(item.number?.trim())
    return !item.number?.trim() || num < 0
  })

  if (hasEmptyNumber) {
    message.warning(t('opticore.workReport.table.number'))
    return
  }

  let data = finishList.value.map((item) => {
    return {
      serialNo: item.serialNo,
      itemCode: item.itemCode,
      itemName: item.itemName,
      lastLen: item.number,
      docNo: item.docNo
    }
  })

  console.log('data', data)

  DeviceApi.getcheckLenList(data).then((res) => {
    if (res) {
      message.success(t('opticore.workReport.table.finishSuccess'))
      showFinishDialog.value = false
      finishList.value = []
    }
  })
}

const querySearch = (queryString, cb) => {
  let suggestions = []

  if (mode.value == 'report') {
    suggestions = reportList.value
  } else if (mode.value == 'start') {
    suggestions = kgList.value
  } else {
    suggestions = reportList.value
  }

  // 过滤逻辑
  const filtered = queryString
    ? suggestions.filter((item) => item.value.toLowerCase().includes(queryString.toLowerCase()))
    : suggestions

  // 调用回调返回结果
  cb(filtered)
}
const handleSelect = (item) => {
  // 处理选择事件
  serial.value = item.value
}

//报工表单
const form = ref({
  serialId: '',
  workOrder: '', //工单号
  quantity: '',
  itemCode: '',
  operator: JSON.parse(localStorage.getItem('userInfo')).nickname // 默认值
})

const showStartDialog = ref(false)

const workStartFormRef = ref()

const canStart = ref(true)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await WorkReportApi.getWorkReportPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const fetchProductLineList = async () => {
  try {
    const result = await getLineDictDataList()
    productLineList.value = result.map((item) => ({
      id: item.id, // 产线id
      label: item.label // 产线名称
    }))
    console.log('产线数据 productLineList.value:', productLineList.value)
  } finally {
  }
}

const fetchDeviceList = async () => {
  queryParams.pageNo = 1
  queryParams.pageSize = 1000
  const data = await DeviceApi.getDevicePage(queryParams)
  deviceList.value = data.list
}

const fetchProcessList = async () => {
  try {
    processList.value = await ProcessInfoApi.fetchProcessNameList()
  } finally {
  }
}

/** 报工逻辑 */
const handleReport = async () => {
  if (queryParams.lineId === undefined || queryParams.lineId === null) {
    message.warning(t('opticore.workReport.message.selectLine'))
    return
  }

  if (queryParams.equipment === undefined || queryParams.equipment === null) {
    message.warning(t('opticore.workReport.message.selectEquipment'))
    return
  }

  if (queryParams.process === undefined || queryParams.process === null) {
    message.warning(t('opticore.workReport.message.selectProcess'))
    return
  }

  if (serial.value === '') {
    message.warning(t('opticore.workReport.message.scanSerial'))
    return
  }

  console.log(serial.value)
  const serialNo = await fetchMaterialsInfoBySerialId(serial.value)
  if (!serialNo) {
    showReportDialog.value = true
    return
  }
  form.value.serialId = serialNo
  // form.value.workOrder = serial.value
  //获取工单号
  showReportDialog.value = true
}

const fetchMaterialsInfoBySerialId = async (serialId) => {
  if(!reportList.value||reportList.value.length==0){
      message.error(t('opticore.workReport.dialog.noOrder'))
      serial.value = ''
      return
    }
  const data = await MaterialUsageApi.getMaterialInfoBySerialNo(reportList.value[0].value)
  if (data == null) {
    message.error(t('opticore.workReport.dialog.invalidWorkOrder') + `: ${serialId}`) 
    serial.value = ''
    return
  }
  form.value.itemCode = data.itemCode
  form.value.workOrder = data.docNo
  return serialId == data.docNo?data.serialNo:serialId
}

// 报工逻辑提交
const handleSubmit = async () => {
  const reportVo = reactive({
    serialNo: form.value.serialId,
    docNo: form.value.workOrder,
    lineId: queryParams.lineId,
    equipment: queryParams.equipment,
    process: queryParams.process,
    processCode: queryParams.processCode,
    qty: form.value.quantity,
    itemCode: form.value.itemCode,
    updater: form.value.operator,
    productId: productIdNew.value
  })
  console.log('提交报工参数', reportVo)
  const data = reportVo as unknown as WorkReportVO
  await WorkReportApi.createWorkReport(data)

  //报工后 更新工单状态完成
  const res = await WorkReportApi.updateWorkReportStatus(data.docNo)
  console.log('报工后 更新工单状态完成', res)

  message.success(t('opticore.workReport.message.reportSuccess'))
  showReportDialog.value = false
  form.value.quantity = ''
  // 发送操作成功的事件
  // emit('success')
  printCode(reportVo)
}

const printDialogVisible = ref(false)
const selectedMaterialsItem = ref<any>({})
/** 打印方法 */
const printCode = (item: any) => {
  console.log(item)
  selectedMaterialsItem.value = item
  printDialogVisible.value = true
}
function resetState() {
  printDialogVisible.value = false
  console.log(printDialogVisible.value)
}

const handleClose = (done) => {
  // 可以添加关闭前的确认逻辑
  form.value.quantity = ''
  done()
}

const handleStart = async () => {
  if (!queryParams.lineId ) {
    message.warning(t('opticore.workReport.message.selectLine'))
  return
  }
  if (!queryParams.equipment ) {
    message.warning(t('opticore.workReport.message.selectEquipment'))
  return
  }
  // 检查工序是否有值
  if (!queryParams.process) {
    message.warning(t('opticore.workReport.message.selectProcessFirst'))
    return
  }
  console.log('工序值', queryParams.process, queryParams.processCode)

  // 获取选中的产线名称
  const selectedLine = productLineList.value.find((item) => item.id === queryParams.lineId)
  const lineName = selectedLine ? selectedLine.label : ''

  // 重新检查是否存在开工记录
  const res = await WorkReportApi.getWorkInfoBySerialNo(serial.value,queryParams.lineId)
  if (res && res.isWorkInfo) {
    message.warning(t('opticore.workReport.message.existWorkInfo'))
    return
  }

  // 传递参数，带上产线id和产线名称
  workStartFormRef.value.open({
    ...queryParams,
    lineName,
    processCode: res.processCode
  })
}

/** 初始化 **/
onMounted(() => {
  getList()
  fetchProductLineList()
  fetchDeviceList()
  fetchProcessList()
})

const productIdNew = ref()

// 监听物料序列号变化
// watch(serial, async (newVal) => {
//   queryParams.serialNo = newVal

//   // 新增校验逻辑：检查产线设备是否已填
//   if (newVal && (!queryParams.lineId || !queryParams.equipment || !queryParams.process)) {
//     message.warning('请先选择产线,设备和工序')
//     serial.value = '' // 清空序列号
//     return
//   }

//   if (newVal) {
//     // 获取选中的产线名称
//     const selectedLine = productLineList.value.find((item) => item.id === queryParams.lineId)
//     const lineName = selectedLine ? selectedLine.label : ''

//     const res = await WorkReportApi.getWorkInfoBySerialNo(newVal,queryParams.lineId)
//     if (res && res.isWorkInfo) {
//       //存在开工记录
//       canStart.value = false
//       // queryParams.process = res && res.workSerial ? res.workSerial : undefined
//       // queryParams.processCode = res && res.workSerialCode ? res.workSerialCode : undefined
//       productIdNew.value = res.productId
//     } else {
//       canStart.value = true
//       // queryParams.process = res && res.workSerial ? res.workSerial : undefined
//       // queryParams.processCode = res && res.workSerialCode ? res.workSerialCode : undefined
//       queryParams.docNo = res?.doc_no || undefined
//       queryParams.productId = res.productId || null
//       productIdNew.value = res.productId
//     }
//     console.log('查看工序', queryParams, res.workSerialCode)
//   } else {
//     // queryParams.process = undefined
//     canStart.value = true
//   }
// })
</script>
<style scoped lang="less">
.content-wrapper-1 {
  height: 90vh;

  padding: 20px;

  margin: 77px 16px 16px 16px;

  background-color: #fff;
}
.serial-number {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  margin-top: 50px; /* 调整上边距 */
  margin-bottom: 40px;
  color: #333;
}

.report-btn-container {
  text-align: center;
  margin-bottom: 30px; /* 增加底部间距 */
}

.report-btn {
  width: 270px;
  height: 160px;
  font-size: 48px;
}

.serial-input {
  width: 500px; /* 调整宽度 */
  height: 50px; /* 调整高度 */
  font-size: 18px; /* 增大字体 */
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  outline: none;
  transition: border-color 0.2s;
}

.form-container {
  padding: 10px 20px;
}

.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.form-label {
  width: 80px;
  font-size: 14px;
  color: #606266;
  flex-shrink: 0;
}

.form-value {
  flex-grow: 1;
  height: 40px;
  line-height: 40px;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #606266;
  border: 1px solid #dcdfe6;
}

.form-input {
  flex-grow: 1;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.el-dialog__footer {
  text-align: center;
}

 
    @media (min-width: 768px) {
     
    }

 
    @media (min-width: 1024px) {
 
    }
</style>
